/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package cn.icanci.learn.v1.aop4;

import cn.icanci.learn.v1.aop3.TargetMethod;

import java.lang.reflect.InvocationTargetException;
import java.util.List;

/**
 * @author icanci
 * @date Created in 2021/06/27 22:37
 * @version 1.0
 */
public class MyMethodInvocationImpl implements MyMethodInvocation {

    private TargetMethod              targetMethod;

    private List<MyMethodInterceptor> interceptors;

    private int                       index = 0;

	public MyMethodInvocationImpl(TargetMethod targetMethod, List<MyMethodInterceptor> interceptors) {
		this.targetMethod = targetMethod;
		this.interceptors = interceptors;
	}

	/**
     * proceed 驱动连接器链，执行增强逻辑和被代理方法调用
     * @return Object
     */
    @Override
    public Object proceed() throws InvocationTargetException, IllegalAccessException {
        // 拦截器执行完毕，接下来要执行被代理的方法
        if (index == interceptors.size()) {
            return targetMethod.getMethod().invoke(targetMethod.getTarget(), targetMethod.getArgs());
        }
        // 到这里，说明还有拦截器，为执行
        final MyMethodInterceptor myMethodInterceptor = interceptors.get(index++);
        return myMethodInterceptor.invoke(this);
    }

    public void setInterceptors(List<MyMethodInterceptor> interceptors) {
        this.interceptors = interceptors;
    }
}
